package com.yedean.response.interceptor;

import com.yedean.tenant.TenantContext;
import com.yedean.utils.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.dubbo.rpc.RpcContext;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * shopId拦截器
 *
 * @author yedean
 * @date 2022/9/15
 */
@Slf4j
@Component
public class WebHandlerInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //获取jwt
        String tokenInfo = request.getHeader("Authorization");

        if (StringUtils.isNotEmpty(tokenInfo)) {

            try {

                //解析令牌
                Map<String, Object> tokenMap = JWTUtil.decode(tokenInfo);
                //放入租户上下文
                TenantContext.addAttachments(tokenMap);
            } catch (Exception e) {
                log.error("解析令牌失败");
                e.printStackTrace();
            }
        }
        return true;
    }
}
